#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Vergil
# datetime:2018/9/23 15:51
# software: PyCharm
import random
from urllib.parse import urlparse, parse_qsl
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait

import logging
import requests
import time

logger = logging.getLogger('main.p_click')

reply_list = ['真的非常感谢，学到了很多。',
              '每个人的看法不同吧，我个人认为不能凭主观意识判断。',
              '哇，膜拜大佬的操作。',
              '谢谢楼主的分享，又学习到了新的技能。',
              '陈独秀同学请你坐下，你挡住后面的李大钊同学发言了。',
              '看完之后深有感触，不说了，我要去拯救世界了。',
              '感慨良多，很棒的分享。',
              '原来如此，果然我还是太弱了。',
              '看了楼主的帖，我意识到自己还有许许多多要学习的！',
              '我也觉得是这样',
              '学到了，谢谢哦',
              '可以试试',
              '有点难诶',
              '对。就是这样']


def post_click(driver, url_lst, headers, browse_times):
    """
    :param driver:
    :param url_lst:所有帖子列表
    :param headers: POST请求所需
    :return:
    """

    logger.info('------开始刷帖------')
    click_times = 0

    for i in range(len(url_lst)):
        post_url = url_lst[i]
        if click_times < int(browse_times):
            driver.get(post_url)
            try:
                if driver.current_url == post_url:
                    post_brush(driver, post_url, headers)
                else:
                    driver.get(post_url)
                    time.sleep(2)
                    post_brush(driver, post_url, headers)

                logger.info('>>>>>>>>已经点击%s次<<<<<<<<<' % str(click_times+1))
                click_times += 1
                time.sleep(2)

            except Exception as e:
                logger.exception(e)
        else:
            break


def post_brush(driver, post_url, headers):
    """
    :param driver:
    :param post_url: 单独帖子URL
    :param headers: POST请求所需
    :return:
    """
    try:
        result = urlparse(post_url)
        parameter_tuple = parse_qsl(result[4])
        # 将参数元组第一个元素中的第二个元素赋给forum_id，后面post请求必须要此参数
        forum_id = parameter_tuple[0][1]
        threa_id = parameter_tuple[1][1]

        wait = WebDriverWait(driver, 10)
        element = wait.until(
            EC.presence_of_element_located(
                (By.XPATH, '//div[@class="panel-body col-md-12"]/table')))
        post_elements = element.find_element_by_tag_name(
            'tbody').find_elements_by_tag_name('p')

        logger.info('----共有%s篇回复----' % str(len(post_elements)))

        if len(post_elements) > 15:  # 判断帖子是否有超过一页的回复，如果有，复制第一页随机楼层的回复。若无，回复自定义内容。
            reply_element = post_elements[random.randint(1, 14)]
            reply = reply_element.text
        else:
            logger.info('此贴回复过少，将回复自定义内容')
            reply = random.choice(reply_list)

        post_ids = driver.find_element_by_xpath(
            '//div[@id="postList"]/div/div[@class="panel-footer"]/input').get_attribute('value')  # 截取发帖人发帖内容的id列表
        post_id = post_ids[0:8]

        url = 'https://spoc.tfswufe.edu.cn/JiaoXue/Forum/ReplyPost'

        data = {
            'postId': post_id,
            'currentForumId': forum_id,
            'threadId': threa_id,
            'isFirstPost': 1,
            'position': 0,
            'parentId': 0,
            'content': '<p>%s</p>' % reply}

        r = requests.post(url, data=data, headers=headers)

        logger.info(r.status_code)

    except Exception as e:
        logger.exception(e)


def main(driver, url_lst, headers, browse_times):
    driver = driver
    post_click(driver, url_lst, headers, browse_times)
    logger.info('>>>>>>刷帖完成<<<<<<')
